package com.ews.onlineexchange.controller;

import java.text.NumberFormat;
import java.util.List;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
import javax.persistence.Query;

import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.Sector;
import com.ews.onlineexchange.service.EntityHome;

@Named
@ConversationScoped
public class ParentSectorHome extends EntityHome<Sector, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private static NumberFormat nf;
	static {
		nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(0);
		nf.setMinimumIntegerDigits(4);
		nf.setGroupingUsed(false);
	}
	
	private Sector oldParent;
	
	private static final String QUERY_ROOT_SECTORS_EQL = ""
			+ "	FROM 	Sector sector"
			+ "	WHERE	sector.parentSector IS NULL ";
	
//	@Produces
	@Named
	public List<Sector> getRootSectorList() {
		return getEntityManager().createQuery(QUERY_ROOT_SECTORS_EQL).getResultList();
	}

	@Override
	public Sector loadInstance() {
		Sector loadInstance = super.loadInstance();
		if (loadInstance != null)
			this.setOldParent(loadInstance.getParentSector());
		return loadInstance;
	}

	@Override
	public String saveAndFlush() {
		Sector newParent = this.getInstance().getParentSector();
		if (!isManaged() || newParent != getOldParent() || !newParent.equals(oldParent)) {
			getInstance().setSno(getNextSno(getInstance().getParentSector()));
		}
		return super.saveAndFlush();
	}

	private static final String QUERY_MAX_SNO_EQL = ""
			+ "	SELECT		COUNT(sector.id)	"
			+ "	FROM		Sector sector"
			+ "	WHERE		(sector.parentSector = :parentSector OR (:parentSector IS NULL AND sector.parentSector IS NULL ))";
	
	
	private String getNextSno(Sector parentSector) {
		Query query = getEntityManager().createQuery(QUERY_MAX_SNO_EQL);
		query.setParameter("parentSector", parentSector);
		Long count = (Long) query.getSingleResult();
		String result = nf.format(count + 1);
		if (parentSector != null)
			result = parentSector.getSno().concat(result);
		return result;
	}

	@Override
	public String delete() {
		getInstance().setDelFlag(DataEntity.DEL_FLAG_DELETE);
		String result = super.saveAndFlush();
		if (result.equals("saved"))
			return "deleted";
		return null;
	}

	public Sector getOldParent() {
		return oldParent;
	}

	public void setOldParent(Sector oldParent) {
		this.oldParent = oldParent;
	}
	
	private static final String QUERY_ALL_ROOT_SECTORS_EQL = ""
			+ "	FROM 	Sector sector ORDER BY sno,createDate DESC";
	
	@Named
	public List<Sector> getAllSectorList() {
		return getEntityManager().createQuery(QUERY_ALL_ROOT_SECTORS_EQL).getResultList();
	}
}
